package com.ds.bpm.plugins.listener;

import com.ds.common.JDSException;
import com.ds.common.util.StringUtility;
import com.ds.config.*;
import com.ds.enums.db.MethodChinaName;
import com.ds.esd.bpm.BPMFactory;
import com.ds.esd.client.ESDFacrory;
import com.ds.esd.client.ProjectVersion;
import com.ds.esd.custom.annotation.CustomAnnotation;
import com.ds.esd.custom.annotation.DialogAnnotation;
import com.ds.esd.custom.annotation.FormViewAnnotation;
import com.ds.esd.custom.annotation.GridViewAnnotation;
import com.ds.esd.custom.api.annotation.APIEventAnnotation;
import com.ds.esd.custom.api.enums.CustomCallBack;
import com.ds.esd.custom.enums.CustomMenuItem;
import com.ds.esd.custom.module.annotation.ModuleAnnotation;
import com.ds.web.util.PageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;


@RequestMapping("/admin/bpd/listener/")
@Controller
@MethodChinaName(cname = "监听器", imageClass = "bpmfont bpm-gongzuoliu-moxing")
public class ListenerManager {

    @CustomAnnotation(pid = true, hidden = true)
    private String projectId;

    @RequestMapping("Listeners")
    @GridViewAnnotation
    @ModuleAnnotation(imageClass = "bpmfont bpm-gongzuoliu-moxing", caption = "监听器")
    @ResponseBody
    @APIEventAnnotation(autoRun = true, bindMenu = {CustomMenuItem.treeNodeEditor})
    public ListResultModel<List<ListenerGridView>> getListeners(String projectName, String listenerType) {
        ListResultModel<List<ListenerGridView>> result = new ListResultModel<List<ListenerGridView>>();
        ListenerType type = ListenerType.EXPRESSION;
        if (listenerType != null) {
            type = ListenerType.fromType(listenerType);
        }


        BPDProjectConfig config = null;
        try {
            ProjectVersion version = ESDFacrory.getESDClient().getProjectVersionByName(projectName);
            config = this.getConfig(version.getProject().getId());
            if (config != null) {
                switch (type) {
                    case RIGHT:
                        result = PageUtil.getDefaultPageList(config.getRightListeners(), ListenerGridView.class);
                        break;
                    case ACTIVITY:
                        result = PageUtil.getDefaultPageList(config.getActivityListeners(), ListenerGridView.class);
                        break;
                    case PROCESS:
                        result = PageUtil.getDefaultPageList(config.getProcessListeners(), ListenerGridView.class);
                        break;

                    case EXPRESSION:
                        result = PageUtil.getDefaultPageList(config.getBpdListeners(), ListenerGridView.class);
                        break;

                }

            }

        } catch (JDSException e) {
            result = new ErrorListResultModel();
            ((ErrorListResultModel<List<ListenerGridView>>) result).setErrdes(e.getMessage());
        }
        return result;
    }


    @MethodChinaName(cname = "添加监听器")
    @RequestMapping(method = RequestMethod.POST, value = "saveListener")
    @APIEventAnnotation(callback = {CustomCallBack.ReloadParent, CustomCallBack.Close}, bindMenu = {CustomMenuItem.save})
    @ResponseBody
    public ResultModel<Boolean> saveListener(@RequestBody ListenerFormView listenerView) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        String projectId = listenerView.getProjectId();

        try {
            BPDProjectConfig config = BPMFactory.getInstance().getProjectConfig(projectId);
            CListener listener = new CListener();
            String listenerId = listenerView.getListenerId();
            if (listenerId == null || listenerId.equals("")) {
                listenerId = UUID.randomUUID().toString();
            }
            listener.setImplementation(listenerView.getImplementation());
            listener.setListenerId(listenerId);
            listener.setListenerType(listenerView.getListenerType());
            listener.setName(listenerView.getName());
            listener.setProjectId(listenerView.getProjectId());
            List<CListener> listeners = new ArrayList<>();
            switch (listenerView.getListenerType()) {
                case RIGHT:
                    listeners = config.getRightListeners();
                    break;
                case ACTIVITY:
                    listeners = config.getActivityListeners();
                    break;
                case PROCESS:
                    listeners = config.getProcessListeners();
                    break;

                case EXPRESSION:
                    listeners = config.getBpdListeners();
                    break;

            }

            CListener oldListener = null;
            for (CListener cListener : listeners) {
                if (cListener.getListenerId().equals(listener)) {
                    oldListener = cListener;
                }
            }
            if (oldListener != null) {
                listeners.remove(oldListener);
            }
            listeners.add(listener);

            BPMFactory.getInstance().updateProjectConfig(config);
        } catch (JDSException e) {
            e.printStackTrace();
        }

        return result;
    }


    @RequestMapping(method = RequestMethod.POST, value = "AddListener")
    @APIEventAnnotation(bindMenu = {CustomMenuItem.add, CustomMenuItem.editor})
    @FormViewAnnotation
    @DialogAnnotation(height = "260", width = "350")
    @ModuleAnnotation(caption = "添加监听器")
    @ResponseBody
    public ResultModel<ListenerFormView> addListener(String projectId, String pluginId, String listenerType) {
        ResultModel<ListenerFormView> result = new ResultModel<ListenerFormView>();

        try {
            BPDProjectConfig config = BPMFactory.getInstance().getProjectConfig(projectId);
            CListener listener = new CListener();
            String listenerId = UUID.randomUUID().toString();

            listener.setListenerId(listenerId);
            ListenerType type = ListenerType.EXPRESSION;
            if (listenerType != null) {
                type = ListenerType.fromType(listenerType);
                listener.setListenerType(type);
            }
            result.setData(new ListenerFormView(listener));
        } catch (JDSException e) {
            e.printStackTrace();
        }

        return result;
    }

    @MethodChinaName(cname = "delListener")
    @RequestMapping(method = RequestMethod.POST, value = "delListener")
    @ResponseBody
    @APIEventAnnotation(callback = {CustomCallBack.Reload})
    public ResultModel<Boolean> delListener(String listenerId, String projectId) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();

        List<String> idarr = Arrays.asList(StringUtility.split(listenerId, ";"));

        try {
            BPDProjectConfig bpdProjectConfig = BPMFactory.getInstance().getProjectConfig(projectId);
            List<CListener> aListeners = new ArrayList<CListener>();
            for (CListener listener : bpdProjectConfig.getActivityListeners()) {
                if (!idarr.contains(listener.getListenerId())) {
                    aListeners.add(listener);
                }
            }
            bpdProjectConfig.setActivityListeners(aListeners);
            List<CListener> pListeners = new ArrayList<CListener>();
            for (CListener listener : bpdProjectConfig.getProcessListeners()) {
                if (!idarr.contains(listener.getListenerId())) {
                    aListeners.add(listener);
                }
            }
            bpdProjectConfig.setProcessListeners(pListeners);


            List<CListener> rListeners = new ArrayList<CListener>();
            for (CListener listener : bpdProjectConfig.getRightListeners()) {
                if (!idarr.contains(listener.getListenerId())) {
                    aListeners.add(listener);
                }
            }
            bpdProjectConfig.setRightListeners(rListeners);


            List<CListener> eListeners = new ArrayList<CListener>();
            for (CListener elistener : bpdProjectConfig.getBpdListeners()) {
                if (!idarr.contains(elistener.getListenerId())) {
                    aListeners.add(elistener);
                }
            }
            bpdProjectConfig.setBpdListeners(rListeners);

            BPMFactory.getInstance().updateProjectConfig(bpdProjectConfig);
        } catch (JDSException e) {
            result = new ErrorResultModel<>();
            ((ErrorResultModel) result).setErrcode(e.getErrorCode());
            ((ErrorResultModel) result).setErrdes(e.getMessage());
        }


        return result;
    }

    BPDProjectConfig getConfig(String projectId) throws JDSException {

        BPDProjectConfig config = BPMFactory.getInstance().getProjectConfig(projectId);
        return config;
    }

    public String getProjectId() {
        return projectId;
    }

    public void setProjectId(String projectId) {
        this.projectId = projectId;
    }
}
